package cn.kgc.vue.shiro;

import jakarta.servlet.Filter;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * @author 课工场
 * @date 2024/9/20
 * @description   shiro权限框架的全局配置
 */
@Configuration
public class ShiroSpringbootConfig {

    //  1. shiro过滤器
    @Bean
    public ShiroFilterFactoryBean  shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        //  设置shiro的安全规则
        LinkedHashMap<String, String> authMap = new LinkedHashMap<>();
        authMap.put("/user/unAuth","anon");
        // 放行验证码请求
        authMap.put("/user/captcha","anon");
        // 放行登录请求
        authMap.put("/user/login","anon");

        // 放行swagger请求
        authMap.put("/doc.html","anon");
        authMap.put("/swagger-resources", "anon");
        authMap.put("/favicon.ico", "anon");
        authMap.put("/v3/api-docs/**", "anon");
        authMap.put("/webjars/**", "anon");

        // 添加自定义的filter
        HashMap<String, Filter> customerFilter = new HashMap<>();
        // key  自定义filter的别名
        customerFilter.put("tkFilter",new TokenFilter());
        shiroFilterFactoryBean.setFilters(customerFilter);

        // authc 权限判定   session  subject.login(token)  tokenFilter
        authMap.put("/**","tkFilter");

        // 设置未认证时 跳转路径
        shiroFilterFactoryBean.setLoginUrl("/user/unAuth");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(authMap);

        return shiroFilterFactoryBean;
    }

    // 2.  web安全管理类
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(CustomerRealm customerRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        defaultWebSecurityManager.setRealm(customerRealm);
        return  defaultWebSecurityManager;
    }

    // 3.自定义realm

    @Bean
    public CustomerRealm customerRealm(){
        CustomerRealm customerRealm = new CustomerRealm();
        return customerRealm;
    }

}
